package com.lt.lumentracks.config;

import com.lt.lumentracks.properties.ElasticSearchProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * es配置类
 */
@Slf4j
@Configuration
public class ElasticSearchConfig {

    @Bean(destroyMethod = "close") //程序开始时交给bean对象注入, 指定了当bean被销毁时应该调用其close方法
    @ConditionalOnMissingBean//保证spring容器里面只有一个utils对象(当没有这个bean对象再去创建，有就没必要去创建了)
    public RestHighLevelClient client(ElasticSearchProperties elasticSearchProperties){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost(
                                elasticSearchProperties.getHost(),
                                elasticSearchProperties.getPort(),
                                "http"
                        )
                )
        );

        // 测试连接是否可用
        try {
            client.ping(RequestOptions.DEFAULT);
            log.info("✅ Elasticsearch 连接成功: {}:{}",
                    elasticSearchProperties.getHost(),
                    elasticSearchProperties.getPort()
            );
        } catch (Exception e) {
            log.error("❌ Elasticsearch 连接失败: {}:{}, error={}",
                    elasticSearchProperties.getHost(),
                    elasticSearchProperties.getPort(),
                    e.getMessage()
            );
            log.error("请检查elasticsearch服务是否可用");
            //throw new RuntimeException("Elasticsearch 连接失败", e);
        }

        return client;
    }

}